import 'dart:io';
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:path_provider/path_provider.dart';

class GSFileSaveUtil {
  // 保存文件
  static Future<File> saveFile(String savePath, Uint8List bytes) async {
    return await File(savePath).writeAsBytes(bytes);
  }

  // 判断目录是否存在，不存在创建目录
  static Future<bool> checkExists(String path) async {
    var file = Directory(path);
    try {
      bool exists = await file.exists();
      if (!exists) {
        await file.create();
        print("创建缓存目录：$path");
        return await checkExists(path);
      } else {
        return true;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }

  // 判断目录是否存在，不存在创建目录
  static Future<bool> checkFileExists(String path) async {
    var file = File(path);
    try {
      return await file.exists();
    } catch (e) {
      return false;
    }
  }

  // 查询缓存目录文件
  static Future<List<FileSystemEntity>> query({@required String path}) async {
    Directory directory = new Directory(path);
    return directory.listSync();
  }

  static bool deleteSync({@required String path}) {
    try {
      File(path).deleteSync();
    } catch (e) {
      return false;
    }
    return true;
  }

  // 图片缓存目录
  static Future<String> imageCachePath() async {
    var dir = (await getApplicationDocumentsDirectory()).path;
    dir = "$dir/cache";
    await GSFileSaveUtil.checkExists(dir);
    dir = "$dir/images";
    await GSFileSaveUtil.checkExists(dir);
    return dir;
  }
}
